﻿using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Sunny.Service;

namespace Sunny.Util.Exception
{
    public class ExceptionHandler:ExceptionFilterAttribute
    {
        private readonly IHostEnvironment _environment;
        private readonly ILogger<ExceptionHandler> _logger;

        public ExceptionHandler(IHostEnvironment environment,ILogger<ExceptionHandler> logger)
        {
            _environment = environment;
            _logger = logger;
        }
        
        public override void OnException(ExceptionContext context)
        {
            
            if(context.Exception is BusinessException exception)
            {
                _logger.LogError(exception,exception.Message);
                context.Result = new JsonResult(exception.CodeMessage);
                context.ExceptionHandled = true;
            }
            else
            {
                _logger.LogError(context.Exception,context.Exception.Message);
                if (_environment.IsDevelopment())
                {
                    context.Result = new JsonResult(Result.Error(context.Exception.Message));
                }
                else
                {
                    context.Result = new JsonResult(Result.Error(CodeMessage.UnknownError));
                    context.ExceptionHandled = true;
                }
            }
        }
    }
}